using B.S.RbacData.Domain.Traceabilitys;
using B.S.RbacData.ErrorCode;
using B.S.RbacData.Infrastructure;
using B.S.RbacData.Read.API.Applications.Commands.Traceabilitys;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace B.S.RbacData.Read.API.Applications.CommandHandlters.Traceabilitys
{
    /// <summary>
    /// 获取溯源详情命令处理器
    /// </summary>
    public class GetTraceabilityDetailCommandHandlter : IRequestHandler<GetTraceabilityDetailCommand, ApiResult<object>>
    {
        private readonly DataDbcontext _dbContext;
        private readonly ILogger<GetTraceabilityDetailCommandHandlter> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        public GetTraceabilityDetailCommandHandlter(
            DataDbcontext dbContext,
            ILogger<GetTraceabilityDetailCommandHandlter> logger)
        {
            _dbContext = dbContext;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取溯源详情命令
        /// </summary>
        public async Task<ApiResult<object>> Handle(GetTraceabilityDetailCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 验证溯源码ID
                if (string.IsNullOrEmpty(request.QrCodeId))
                {
                    return new ApiResult<object>
                    {
                        code = ResultEnumCode.fails,
                        message = "溯源码ID不能为空",
                        data = null
                    };
                }

                // 查询溯源码信息
                var qrCode = await _dbContext.QRCodes
                    .FirstOrDefaultAsync(q => q.UniqueCode == request.QrCodeId && !q.IsDeleted, cancellationToken);

                if (qrCode == null)
                {
                    return new ApiResult<object>
                    {
                        code = ResultEnumCode.NotFind,
                        message = "溯源码不存在或已失效",
                        data = null
                    };
                }

                // 标记溯源码已被使用
                qrCode.IsUsed = true;
                await _dbContext.SaveChangesAsync(cancellationToken);

                // 获取产品信息
                var product = await _dbContext.Products
                    .Include(p => p.Goods)
                    .FirstOrDefaultAsync(p => p.ID == qrCode.ProductId && !p.IsDeleted, cancellationToken);

                if (product == null)
                {
                    return new ApiResult<object>
                    {
                        code = ResultEnumCode.NotFind,
                        message = "产品信息不存在",
                        data = null
                    };
                }

                // 获取养殖信息
                var farmingInfo = await _dbContext.Farmings
                    .FirstOrDefaultAsync(f => f.ProductId == product.ID, cancellationToken);

                // 获取养殖企业信息
                var farmingCorporate = farmingInfo != null
                    ? await _dbContext.FarmingCorporates
                        .FirstOrDefaultAsync(fc => fc.ProductId == product.ID, cancellationToken)
                    : null;

                // 获取养殖相关图片
                var farmingImages = await _dbContext.Images
                    .Where(i => i.ProductId == product.ID && i.ImgType == "2" && !i.IsDel)
                    .ToListAsync(cancellationToken);

                // 获取屠宰信息
                var slaughterInfo = await _dbContext.Slaughters
                    .FirstOrDefaultAsync(s => s.ProductId == product.ID, cancellationToken);

                // 获取屠宰企业信息
                var slaughterCorporate = slaughterInfo != null
                    ? await _dbContext.SlaughterCorporates
                        .FirstOrDefaultAsync(sc => sc.ProductId == slaughterInfo.SlaughterId, cancellationToken)
                    : null;

                // 获取屠宰相关图片
                var slaughterImages = await _dbContext.Images
                    .Where(i => i.ProductId == product.ID && i.ImgType == "3" && !i.IsDel)
                    .ToListAsync(cancellationToken);

                // 获取深加工信息
                var deepProcessingInfo = await _dbContext.DeepProcessings
                    .FirstOrDefaultAsync(dp => dp.ProductId == product.ID, cancellationToken);

                // 获取深加工企业信息
                var deepProcessingCorporate = deepProcessingInfo != null
                    ? await _dbContext.DeepProcessingCorporates
                        .FirstOrDefaultAsync(dpc => dpc.ProductId == product.ID, cancellationToken)
                    : null;

                // 获取深加工相关图片
                var deepProcessingImages = await _dbContext.Images
                    .Where(i => i.ProductId == product.ID && i.ImgType == "4" && !i.IsDel)
                    .ToListAsync(cancellationToken);

                // 获取产品检验报告图片
                var productImages = await _dbContext.Images
                    .Where(i => i.ProductId == product.ID && i.ImgType == "1" && !i.IsDel)
                    .ToListAsync(cancellationToken);

                // 构建返回数据
                var result = new
                {
                    productInfo = new
                    {
                        ID = product.ID,
                        goodsName = product.Goods?.GoodsName,
                        productionBatch = product.ProductionBatch,
                        shelfLifeDay = product.ShelfLifeDay,
                        productionLicenseNumber = product.ProductionLicenseNumber,
                        manufacturer = product.Manufacturer,
                        coverImage = product.CoverImage,
                        completeness = product.Completeness,
                        createTime = product.CreateTime
                    },
                    productImages,
                    farmingInfo,
                    farmingCorporate,
                    farmingImages,
                    slaughterInfo,
                    slaughterCorporate,
                    slaughterImages,
                    deepProcessingInfo,
                    deepProcessingCorporate,
                    deepProcessingImages
                };

                return new ApiResult<object>
                {
                    code = ResultEnumCode.Ok,
                    message = "获取成功",
                    data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError("获取溯源详情异常处理: " + ex.Message);
                return new ApiResult<object>
                {
                    code = ResultEnumCode.fails,
                    message = "获取溯源详情失败: " + ex.Message,
                    data = null
                };
            }
        }
    }
}
